package com.zhainan.springmvc.servlet;

import com.zhainan.springmvc.annotation.RequestMapping;
import com.zhainan.springmvc.annotation.RequestParam;
import com.zhainan.springmvc.bean.HandlerBean;
import com.zhainan.springmvc.utils.ClassUtils;
import com.zhainan.springmvc.view.ViewResolver;
import com.zhainan.springmvc.view.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lvchang on 2016/10/2.
 */
public class DispatcherServlet extends HttpServlet {

    private Map<String, HandlerBean> handlerBeanMap;

    @Override
    public void init() throws ServletException {
        handlerBeanMap = new HashMap<String, HandlerBean>();
        for (String name : ClassUtils.getAllClassesFromPackage("com.zhainan.springmvc.handler")) {
            try {
                Class clz = Class.forName(name);
                for (Method method : clz.getDeclaredMethods()) {
                    RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                    if (requestMapping != null) {
                        String path = requestMapping.value();
                        handlerBeanMap.put(path, new HandlerBean(name, method.getName()));
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doDispatch(req, resp);
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException
    {
        String path = req.getPathInfo();
        HandlerBean handlerBean = handlerBeanMap.get(path);
        if (handlerBean == null)
            handlerBean = new HandlerBean("com.zhainan.springmvc.handler.DefaultHandler", "doService");
        try {
            Class clz = Class.forName(handlerBean.getBeanName());
            for (Method method : clz.getDeclaredMethods()) {
                if (handlerBean.getMethodName().equals(method.getName())) {
                    Parameter[] parameters = method.getParameters();
                    Object[] args = new Object[parameters.length];
                    for (int i = 0; i < parameters.length; i++) {
                        RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
                        if (requestParam != null) {
                            String parameterName = requestParam.value();
                            args[i] = req.getParameter(parameterName);
                        }
                        if (parameters[i].getType() == HttpServletResponse.class) {
                            args[i] = resp;
                        }
                    }
                    ModelAndView view = (ModelAndView) method.invoke(clz.newInstance(), args);
                    new ViewResolver().render(view, req, resp);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
